<template>
  <div>
    <button @click="showEditor = true">打开公式编辑器</button>
    <VueMathjaxBeautiful
      v-model="showEditor"
      :existing-latex="formula"
      @insert="handleInsert"
      title="中小学数学公式编辑器"
      :placeholder="'请输入公式或选择模板'"
    />

    <div class="math-formula">{{ formula }}</div>

    <!-- <div ref="formulaContainer"></div> -->
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { VueMathjaxBeautiful, initMathJax } from 'vue-mathjax-beautiful'
import 'vue-mathjax-beautiful/dist/style.css'

const showEditor = ref(false)
const formula = ref('S = 5 + 5')
const formulaContainer = ref(null)

// 初始化MathJax
let mathJaxInstance = null
onMounted(() => {
  // 确保只初始化一次
  if (!mathJaxInstance) {
    mathJaxInstance = initMathJax({
      // 配置选项，确保与弹窗内部一致
      tex: {
        inlineMath: [['$', '$'], ['\\(', '\\)']],
        displayMath: [['$$', '$$'], ['\\[', '\\]']]
      },
      svg: {
        fontCache: 'global'
      }
    })
  }
  renderFormula()
})

// 处理公式插入
const handleInsert = (latex) => {
  formula.value = latex
  showEditor.value = false
}

// 监听公式变化并重新渲染
watch(formula, () => {
  renderFormula()
})

// 单独的渲染函数
const renderFormula = () => {
  if (formulaContainer.value && mathJaxInstance) {
    formulaContainer.value.innerHTML = `$$${formula.value}$$`
    // 触发MathJax重新渲染
    if (window.MathJax) {
      window.MathJax.typeset([formulaContainer.value])
    }
  }
}
</script>

<style lang="scss">
.math-formula {
  font-size: 16px;
  color: #000;
  line-height: 20px;
  padding: 10px;
  background-color: #f0efef;
}

</style>